﻿// ***********************************************************************
// Assembly         : OSS.BIM
// Author           : tian_
// Created          : 09-06-2018
//
// Last Modified By : tian_
// Last Modified On : 09-06-2018
// ***********************************************************************
// <copyright file="ProjectUpdateBorderPointsCmd.cs" company="北京智帆高科科技有限公司">
//     Copyright © 北京智帆高科科技有限公司 2018
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using OSS.BIM.Business.Utility;
using OSS.BIM.Model;
using OSS.BIM.Utility;
using DevExpress.XtraEditors;
using Osg;
using OSS.BIM.SceneManage;
using ZFGK.VDF.Entity;
using ZFGK.VDF.Geometry;
using ZFGK.VDF.Utility;
using VectorDraw.Geometry;
using VectorDraw.Professional.Constants;
using VectorDraw.Professional.vdFigures;
using VectorDraw.Professional.vdObjects;
using ZFGK.Addins;
using ZFGK.IO;
using ZFGK.osgEarth.Utility;
using ZFGK.OSG.Utility;
using ZFGK.osgEarth.UI;
using ZFGK.OsgVdf.Utility;
using ZFGK.Utility;

namespace OSS.BIM.Commands.ProjcetCmds
{
    /// <summary>
    /// Class ProjectUpdateBorderPointsCmd.
    /// </summary>
    /// <seealso cref="ZFGK.Addins.IExtendCommand" />
    public class ProjectUpdateBorderPointsCmd : IExtendCommand
    {
        /// <summary>
        /// Executes the specified command data.
        /// </summary>
        /// <param name="cmdData">The command data.</param>
        /// <param name="message">The message.</param>
        /// <returns>CmdResult.</returns>
        public CmdResult Execute(ExtendCmdData cmdData, ref string message)
        {
            var osgEarthViewForm = cmdData.ViewForm as OsgEarthViewForm;
            if (osgEarthViewForm == null)
                return CmdResult.Failure;
            var osgEarthViewCtrl = osgEarthViewForm.OsgEarthViewCtrl;
            var osgEarthObj = osgEarthViewCtrl.OsgEarthObj;
            var actionUtility = osgEarthViewCtrl.ActionUtility;
            
            var project = cmdData.Tag as Project;
            if (project == null)
                return CmdResult.Cancel;

            var mapPts = new List<Vec3d>();
            Vec3d mapPt;
            while (actionUtility.PickEarthPointPolygonLastex("选择多边形", mapPts.ToArray(), out mapPt))
                mapPts.Add(mapPt);

            if (mapPts.Count < 3)
            {
                MessageBox.Show("测量面积的点不能小于3", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return CmdResult.Cancel;
            }

            var location = project.GetLocation();
            var rMat = Matrixd.rotate(project.Rotation, new Vec3d() { z = 1 });
            var toWolrdMat = location.CreateLocalToWorld(osgEarthObj.MapNode.getMapSRS());

            var matInv = (rMat * toWolrdMat).GetInvertion();
            var worldPts = mapPts.ToWorld(osgEarthObj.MapNode.getMapSRS());
            matInv.Transform(worldPts);

            foreach (var worldPt in worldPts)
            {
                worldPt.z = 0;
            }

            // 选择要放置的DWG
//             string filePath = null;
//             if (!DialogUtil.OpenDWG(out filePath))
//                 return CmdResult.Cancel;
//             var verts = GetVerts(filePath, null, Color.White);
//             if (verts == null)
//                 return CmdResult.Cancel;

            project.BorderPoints = worldPts.ToJoinString();

            if (ProjectDbUtil.Update(project))
            {
                ZfMessageUtil.ShowAlert("更新边界成功！");
            }

            return CmdResult.Failure;
        }

        /// <summary>
        /// Gets the verts.
        /// </summary>
        /// <param name="tempFilePath">The temporary file path.</param>
        /// <param name="imageFilePath">The image file path.</param>
        /// <param name="color">The color.</param>
        /// <returns>Vec3d[].</returns>
        public static Vec3d[] GetVerts(string tempFilePath, string imageFilePath, Color color)
        {
            var document = vdDocumentUtil.Open(tempFilePath);
            if (document == null)
            {
                XtraMessageBox.Show("打开文件失败\n" + tempFilePath, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }

            var points = GetVerts(document);
            if (points == null)
                return null;

            if (imageFilePath != null)
            {
                DirectoryUtil.EnsureDirExist(Path.GetDirectoryName(imageFilePath));
                document.ActionLayout.BkColorEx = color;
                document.ToImage(points.GetBox()).Save(imageFilePath, ImageFormat.Jpeg);
            }

            return points.ToVec3d().ToArray();
        }

        /// <summary>
        /// Gets the verts.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>gPoint[].</returns>
        public static gPoint[] GetVerts(vdDocument document)
        {
            vdPolyline polyline = null;
            var polylines = document.ActionLayout.Entities.Filter<vdPolyline>(d => d.Layer.Name == "设计线");
            foreach (var vdPolyline in polylines)
            {
                if (vdPolyline.Flag == VdConstPlineFlag.PlFlagCLOSE)
                {
                    polyline = vdPolyline;
                    break;
                }
            }

            if (polyline == null)
            {
                ZfMessageUtil.ShowError("文件的[设计线]图层中没有闭合多段线！");
                return null;
            }

            return polyline.GetPolyVertsAndArcSamplePoints();
        }
    }
}
